<?php

namespace app\reserve\controller;
use think\Controller;
use think\Request;
use app\reserve\model\Orderupto;
use think\Db;


class Uptopay extends Controller{
    public function _initialize()
    {
        parent::_initialize();
        Vendor('WxPay.lib.WxPay#Api');
        Vendor('WxPay.WxPay#JsApiPay');
    }
    /**小程序支付
     * @author crazy
     * @time 2018-08-03
     * @param shop_id 商家的id
     * @param m_id 用户的id
     * @param order_sn 订单号
     */
    public function wxPay(){
        $order = new Orderupto();
        /**获取商家的信息*/
        $product_id = input('post.product_id');
        //$shop_id = 1;
        /**获取用户的信息*/
        $u_id = input('post.u_id');
        $addarray["u_id"] = $u_id;
        $addarray["ordernumber"] = "UPTOZXTXCYZ".time().mt_rand(100,999);
        $addarray["product_id"] = $product_id;
        $addarray["status"] = 0;
        $price = Db::name("onecardproduct")
            ->field("topup,backmoney")
            ->where(["id"=>$product_id])
            ->find();
        $addarray["topup"] = $price["topup"];
        $addarray["backmoney"] = $price["backmoney"];
        $addorder = $order->addOrder($addarray);
        if($addorder){
            $pricereal = intval($price["topup"]*100);
            if(!is_numeric($pricereal)){
                return apiResponse("201","金额有误","");
            }else{
               $data = $this->wxPayBase($pricereal,$u_id,$addarray["ordernumber"]);
                // $data = $this->wxPayBase(1,$u_id,$addarray["ordernumber"]);
                header('Content-Type:application/json; charset=utf-8');
                return $data;
            }
        }else{
            return apiResponse("201","生成订单失败","");
        }
    }

    public function manageOrder(){
        $order = new Orderupto();
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $xml_res = $this->xmlToArray($xml);
        if($xml_res['return_code'] == 'SUCCESS'){
            $w["ordernumber"] = $xml_res["out_trade_no"];
            $res = $order->updateOreder($w);
            if($res){
                $xml = "<xml>
                      <return_code><![CDATA[SUCCESS]]></return_code>
                      <return_msg><![CDATA[OK]]></return_msg>
                    </xml>";
                echo $xml;
            }
        }

    }


    /**
     * @param $xml
     * @return mixed
     * ：将xml转为array
     */
    public function xmlToArray($xml)
    {
        //将XML转为array
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }

    public function wxPayBase($pricereal,$u_id,$ordernumber){
        /**获取商家的信息*/
        if(empty($u_id)){
            return apiResponse('201','参数错误',"");
        }
        /**获取用户的信息*/
        $openid = Db::name("user")
                ->field("openid")
                ->where(['u_id'=>$u_id])
                ->find();
        $callback = 'http://'.$_SERVER['HTTP_HOST'].'/reserve/Uptopay/manageOrder';
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $tools = new \JsApiPay();
        $input->SetOpenid($openid["openid"]);
        $input->SetBody("橙子智能洗车");
        $input->SetAttach("橙子智能洗车");
        $input->SetGoods_tag("橙子智能洗车");
        $input->SetOut_trade_no($ordernumber);
        $input->SetTotal_fee($pricereal);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetNotify_url($callback);
        $input->SetTrade_type("JSAPI");
        $order = \WxPayApi::unifiedOrder($input,6);

        if($order['return_code'] == "FAIL"){
            return apiResponse(201,"未知错误，请联系管理员！",$order);
        }
        if(isset($order['result_code']) && $order['result_code'] == 'FAIL'){
            return apiResponse(201,$order['err_code_des']?$order['err_code_des']:'订单信息错误',"");
        }
        $jsApiParameters = $tools->GetJsApiParameters($order);
        $jsApiParameters = stripslashes($jsApiParameters);
        return apiResponse(200,"成功",$jsApiParameters);
    }
}